/****************************************************
          File Name:47-6-server.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 16 Sep 2014 09:19:21 PM CST
*****************************************************/

#include"binary_fifo.h"

int main(int argc,char *argv[])
{
    int semid, shmid, bytes, xfrs;  // xfrs: transfers
    struct shmseg *shmp;
	int fd;
	
	fd=mkfifo(FIFO,PERM);
	if(fd==-1)
		err("mkfifo");

    shmid=shmget(SHM_KEY,sizeof(struct shmseg),IPC_CREAT|PERM);
    if(shmid==-1)
        err("shmget");

    shmp=shmat(shmid,NULL,0); // no flag specificed
    if(shmp==(void *)-1)
        err("shmat");
	
    for(xfrs=0,bytes=0;;bytes+=shmp->cnt,xfrs++)
    {	
		if(Release()==-1)
			err("release");
		
		shmp->cnt=read(STDIN_FILENO,shmp->buf,BUF_SIZE);
        if(shmp->cnt == -1)
			err("read");

		if(shmp->cnt==0)
			break;
    }
	
	if(shmdt(shmp)==-1)
		err("shmdt");
	if(shmctl(shmid,IPC_RMID,0)==-1)
		err("shmctl");
	if(remove(FIFO)==-1)
		err("remove fifo");
	
    fprintf(stderr,"Sent %d bytes (%d xfrs)\n", bytes, xfrs);
    exit(EXIT_SUCCESS);
}
